package common.YueBao;


import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.xz.common.exception.ServiceException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 悦保OCR调用示例
 * </p>
 */
public class YueBaoOcr {
    private static Logger logger = LoggerFactory.getLogger(YueBaoOcr.class);
    //常量字段
//    private static final String GET_TOKEN_URL = "https://ai.ybinsure.com/s/api/getAccessToken";
    private static final String GET_TOKEN_URL = "https://ai.inspirvision.cn/s/api/getAccessToken";
//    private static final String AUTO_INSURANCE_URL = "https://ai.ybinsure.com/s/api/ocr/policy/autoInsurance";
    private static final String AUTO_INSURANCE_URL = "https://ai.inspirvision.cn/s/api/ocr/policy/autoInsurance";
    //http连接超时时间
    private static final int SO_TIMEOUT = 30 * 1000;
    //数据传输超时时间
    private static final int SO_TIMEOUT_DATA = 30 * 1000;

    public static void main(String[] args) {
//        autoInsurance("https://qykh.shopec.com.cn/image-server/bd.jpg",ACCESS_KEY,ACCESS_SECRET);
    }

    /**
     * <p>
     * 调用悦保OCR接口示例
     * </p>
     */
    public static InsurancePolicy autoInsurance(String imgUrl,String accessKey,String accessSecret)throws Exception {
        logger.info("保单地址："+imgUrl);
        //token秘钥
        String token = getAccessToken(accessKey,accessSecret);
        //图片文件
        Map<String, String> map = new HashMap<>();
        map.put("imgUrl", imgUrl);
        map.put("token", token);
        InsurancePolicy insurancePolicy = autoInsurance(map);
        return insurancePolicy;
    }

    /**
     * <p>
     * 调用悦保鉴权接口示例
     * </p>
     */
    public static String getAccessToken(String accessKey,String accessSecret) {
        Map<String, String> mapParam = new HashMap<>();
        mapParam.put("accessKey",accessKey);
        mapParam.put("accessSecret", accessSecret);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT_DATA)
                .setConnectTimeout(SO_TIMEOUT).setConnectionRequestTimeout(SO_TIMEOUT).build();// 设置请求和传输超时时间
        try {
            StringBuffer stringBuffer = new StringBuffer();
            if (mapParam != null) {
                stringBuffer.append("?");
                for (String key : mapParam.keySet()) {
                    stringBuffer.append(key);
                    stringBuffer.append("=");
                    stringBuffer.append(mapParam.get(key));
                    stringBuffer.append("&");
                }
            }
            String str = stringBuffer.toString();
            String params = str.substring(0, str.length() - 1);
            HttpGet httpGet = new HttpGet(GET_TOKEN_URL + params);
            httpGet.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("GET请求返回值：" + result);
            Map map = JSON.parseObject(result, Map.class);
            if ("0".equals(String.valueOf(map.get("code")))){
                return JSON.parseObject(String.valueOf(map.get("data")), Map.class).get("access_token").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * <p>
     * 发送http post请求
     * </p>
     *
     * @param param 请求参数
     */
    public static InsurancePolicy autoInsurance( Map<String, String> param) throws Exception{
        InsurancePolicy insurancePolicy =new InsurancePolicy();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT_DATA).setConnectTimeout(SO_TIMEOUT).setConnectionRequestTimeout(SO_TIMEOUT).build();// 设置请求和传输超时时间
        HttpPost httpPost = new HttpPost(AUTO_INSURANCE_URL);
        httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            //其他参数
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addPart(key,
                            new StringBody(param.get(key), ContentType.create("text/plain", Consts.UTF_8)));
                }
            }
            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);

            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);

            System.out.println("POST请求返回值：" + result);
            Map map = JSON.parseObject(result, Map.class);
            if ("0".equals(String.valueOf(map.get("code")))){
                Gson gson = new Gson();
                insurancePolicy= gson.fromJson(String.valueOf(map.get("data")), InsurancePolicy.class);
            }else{
                throw new ServiceException("识别失败:"+map.get("message"));
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return insurancePolicy;
    }

}
